<template>
  <el-dialog v-model="importVisible" center title="导入用户" width="30%" :before-close="uploadCancel">
    <div class="text-center" v-loading="loading">
      <el-upload :auto-upload="false" accept=".xls, .xlsx" :on-change="upload"
                 v-model:file-list="importFormData.files"
                 class="upload-demo"
                 drag ref="uploadList"
                 :limit="1">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">请上传 xls/xlsx 文件</div>
      </el-upload>
    </div>
    <div class="dialog-footer" slot="footer">
      <el-button :disabled="loading" @click="importList" size="" type="primary">确 定</el-button>
      <el-button :disabled="loading" @click="handleCancel" size="">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script setup>
import {computed, ref} from "vue";
import {ElMessage} from "element-plus";
import {uploadUser} from "@/api/index.js";

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(['update:modelValue']);

// 对话框显示状态
const importVisible = computed({
  get() {
    return props.modelValue;
  },
  set(value) {
    emit('update:modelValue', value);
  }
});

// 加载状态
const loading = ref(false);
// 上传组件引用
const uploadList = ref(null);
// 存储待上传的文件
const importFormData = {
  files: []
};

// 自定义上传方法
const upload = (file, fileList) => {
  console.log(1222)
  const fileExtension = file.name.split('.').pop().toLowerCase();
  if (fileExtension === 'xls' || fileExtension === 'xlsx') {
    console.log(file)
  } else {
    ElMessage.warning('请上传 xls 或 xlsx 格式的文件');
    uploadList.value.clearFiles();
  }
};

// 导入文件方法
const importList = async () => {
  if (!importFormData.files.length) {
    ElMessage.warning('请选择要上传的文件');
    return;
  }
  try {
    loading.value = true;
    const formData = new FormData();
    formData.append('file', importFormData.files[0].raw);

    // 替换为实际的上传接口地址
    const response = await uploadUser(formData);

    if (response.data.code === 200) {
      ElMessage.success('文件上传成功');
      importVisible.value = false;
      // 清空文件选择
      uploadList.value.clearFiles();
    } else {
      ElMessage.error('文件上传失败');
    }
  } catch (error) {
    console.error('上传文件时出错:', error);
    ElMessage.error('文件上传出错，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 点击对话框关闭按钮的处理方法
const uploadCancel = () => {
  importVisible.value = false;
  uploadList.value.clearFiles();
  ElMessage.info('已取消文件选择');
};

const handleCancel = () => {
  importVisible.value = false;
  uploadList.value.clearFiles();
  ElMessage.info('已取消文件选择');
};

</script>

<style scoped>
.dialog-footer {
  text-align: center;
}
</style>